from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTableWidget, 
                               QTableWidgetItem, QLabel, QComboBox, QPushButton,
                               QHeaderView, QTextEdit, QSplitter, QGroupBox)
from PySide6.QtCore import Qt
from PySide6.QtGui import QColor, QFont
from datetime import datetime
from typing import List, Dict, Any
from backend.data_manager import DataManager, ChangeType


class ChangeHistoryDialog(QDialog):
    """变更历史对话框"""
    
    def __init__(self, data_manager: DataManager, parent=None):
        super().__init__(parent)
        self._data_manager = data_manager
        self._setup_ui()
        self._load_change_history()
        
    def _setup_ui(self):
        """设置UI"""
        self.setWindowTitle("数据变更历史")
        self.setMinimumSize(800, 600)
        
        layout = QVBoxLayout(self)
        
        # 顶部控制栏
        control_layout = QHBoxLayout()
        
        # 日期选择
        control_layout.addWidget(QLabel("选择日期:"))
        self._date_combo = QComboBox()
        self._date_combo.currentTextChanged.connect(self._on_date_changed)
        control_layout.addWidget(self._date_combo)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新")
        refresh_btn.clicked.connect(self._load_change_history)
        control_layout.addWidget(refresh_btn)
        
        # 清空按钮
        clear_btn = QPushButton("清空修改标记")
        clear_btn.clicked.connect(self._clear_modification_flags)
        control_layout.addWidget(clear_btn)
        
        control_layout.addStretch()
        layout.addLayout(control_layout)
        
        # 主要内容区域
        splitter = QSplitter(Qt.Horizontal)
        
        # 左侧：变更列表
        left_group = QGroupBox("变更记录")
        left_layout = QVBoxLayout(left_group)
        
        self._change_table = QTableWidget()
        self._change_table.setColumnCount(5)
        self._change_table.setHorizontalHeaderLabels([
            "时间", "类型", "位置", "操作", "描述"
        ])
        
        # 设置表格属性
        self._change_table.setSelectionBehavior(QTableWidget.SelectRows)
        self._change_table.setAlternatingRowColors(True)
        self._change_table.horizontalHeader().setStretchLastSection(True)
        self._change_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        
        # 连接选择事件
        self._change_table.itemSelectionChanged.connect(self._on_selection_changed)
        
        left_layout.addWidget(self._change_table)
        splitter.addWidget(left_group)
        
        # 右侧：详细信息
        right_group = QGroupBox("详细信息")
        right_layout = QVBoxLayout(right_group)
        
        self._detail_text = QTextEdit()
        self._detail_text.setReadOnly(True)
        right_layout.addWidget(self._detail_text)
        
        splitter.addWidget(right_group)
        
        # 设置分割器比例
        splitter.setSizes([400, 400])
        layout.addWidget(splitter)
        
        # 底部状态栏
        self._status_label = QLabel("就绪")
        layout.addWidget(self._status_label)
        
    def _load_change_history(self):
        """加载变更历史"""
        # 获取可用日期
        import os
        import glob
        
        change_files = glob.glob("changes_*.json")
        dates = []
        for file in change_files:
            date = file.replace("changes_", "").replace(".json", "")
            dates.append(date)
        
        dates.sort(reverse=True)
        
        # 更新日期选择框
        self._date_combo.clear()
        if dates:
            self._date_combo.addItems(dates)
            if not self._date_combo.currentText():
                self._date_combo.setCurrentText(dates[0])
        else:
            self._date_combo.addItem(datetime.now().strftime('%Y%m%d'))
        
        # 加载当前日期的变更记录
        self._on_date_changed(self._date_combo.currentText())
        
    def _on_date_changed(self, date: str):
        """日期改变事件"""
        if not date:
            return
            
        changes = self._data_manager.get_change_history(date)
        self._populate_change_table(changes)
        
    def _populate_change_table(self, changes: List[Dict[str, Any]]):
        """填充变更表格"""
        self._change_table.setRowCount(len(changes))
        
        for row, change in enumerate(changes):
            # 时间
            timestamp = change.get('timestamp', '')
            if timestamp:
                try:
                    dt = datetime.fromisoformat(timestamp)
                    time_str = dt.strftime('%H:%M:%S')
                except:
                    time_str = timestamp
            else:
                time_str = ''
            
            self._change_table.setItem(row, 0, QTableWidgetItem(time_str))
            
            # 类型
            change_type = change.get('change_type', '')
            type_item = QTableWidgetItem(self._get_change_type_name(change_type))
            type_item.setData(Qt.UserRole, change_type)
            self._change_table.setItem(row, 1, type_item)
            
            # 位置
            row_index = change.get('row_index')
            col_index = change.get('column_index')
            if row_index is not None and col_index is not None:
                position = f"[{row_index}, {col_index}]"
            elif row_index is not None:
                position = f"行 {row_index}"
            elif col_index is not None:
                position = f"列 {col_index}"
            else:
                position = "全局"
            
            self._change_table.setItem(row, 2, QTableWidgetItem(position))
            
            # 操作
            user_action = change.get('user_action', '')
            self._change_table.setItem(row, 3, QTableWidgetItem(user_action))
            
            # 描述
            description = change.get('description', '')
            self._change_table.setItem(row, 4, QTableWidgetItem(description))
            
            # 设置行颜色
            self._set_row_color(row, change_type)
            
        self._status_label.setText(f"共 {len(changes)} 条变更记录")
        
    def _get_change_type_name(self, change_type: str) -> str:
        """获取变更类型的中文名称"""
        type_names = {
            ChangeType.INSERT.value: "插入",
            ChangeType.UPDATE.value: "更新",
            ChangeType.DELETE.value: "删除",
            ChangeType.COLUMN_ADD.value: "添加列",
            ChangeType.COLUMN_REMOVE.value: "删除列",
            ChangeType.COLUMN_REORDER.value: "重排列",
            ChangeType.COLUMN_MARK.value: "标记列"
        }
        return type_names.get(change_type, change_type)
        
    def _set_row_color(self, row: int, change_type: str):
        """设置行颜色"""
        colors = {
            ChangeType.INSERT.value: QColor(200, 255, 200),  # 浅绿色
            ChangeType.UPDATE.value: QColor(255, 255, 200),  # 浅黄色
            ChangeType.DELETE.value: QColor(255, 200, 200),  # 浅红色
            ChangeType.COLUMN_ADD.value: QColor(200, 200, 255),  # 浅蓝色
            ChangeType.COLUMN_REMOVE.value: QColor(255, 200, 255),  # 浅紫色
            ChangeType.COLUMN_REORDER.value: QColor(255, 220, 200),  # 浅橙色
            ChangeType.COLUMN_MARK.value: QColor(200, 255, 255)  # 浅青色
        }
        
        color = colors.get(change_type, QColor(255, 255, 255))
        for col in range(self._change_table.columnCount()):
            item = self._change_table.item(row, col)
            if item:
                item.setBackground(color)
                
    def _on_selection_changed(self):
        """选择改变事件"""
        current_row = self._change_table.currentRow()
        if current_row >= 0:
            # 获取当前日期的变更记录
            date = self._date_combo.currentText()
            changes = self._data_manager.get_change_history(date)
            
            if current_row < len(changes):
                change = changes[current_row]
                self._show_change_detail(change)
                
    def _show_change_detail(self, change: Dict[str, Any]):
        """显示变更详情"""
        detail_text = f"""
变更详情:
==========

时间: {change.get('timestamp', '')}
类型: {self._get_change_type_name(change.get('change_type', ''))}
操作: {change.get('user_action', '')}
描述: {change.get('description', '')}

位置信息:
---------
行索引: {change.get('row_index', 'N/A')}
列索引: {change.get('column_index', 'N/A')}

数据变更:
---------
旧值: {change.get('old_value', 'N/A')}
新值: {change.get('new_value', 'N/A')}

完整行数据:
----------
"""
        
        full_row_data = change.get('full_row_data')
        if full_row_data:
            detail_text += "\n".join([f"  {i}: {value}" for i, value in enumerate(full_row_data)])
        else:
            detail_text += "N/A"
            
        self._detail_text.setPlainText(detail_text)
        
    def _clear_modification_flags(self):
        """清空修改标记"""
        self._data_manager.clear_modification_flags()
        self._status_label.setText("修改标记已清空") 